from . import db
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask import current_app

class Info(db.Model):
    __tablename__ = 'infos'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32), index=True)
    platform = db.Column(db.Integer)
    short_phone = db.Column(db.String(32))
    long_phone = db.Column(db.String(32))
    address = db.Column(db.String(32))
    questions = db.Column(db.Text)
    status = db.Column(db.Integer, default=0)
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    woker_id = db.Column(db.Integer, db.ForeignKey('users.id'))

    def __repr__(self):
        return '<Info %r>' %self.name

    def to_json(self):
        if self.platform == 0:
            platform = '电脑'
        else:
            platform = '手机'
        json_info = {
            'id': self.id,
            'name': self.name,
            'platform': platform,
            'short_phone': self.short_phone,
            'long_phone':  self.long_phone,
            'address': self.address,
            'question': self.questions,
            'status': self.status,
            'timestamp': self.timestamp
        }
        return json_info

    @staticmethod
    def generate_fake(count=10):
        from sqlalchemy.exc import IntegrityError
        from random import seed
        import forgery_py

        seed()
        for i in range(count):
            info = Info(
                address=forgery_py.address.city(),
                types=0,
                short_phone=forgery_py.address.phone(),
                long_phone=forgery_py.address.phone(),
                name=forgery_py.name.full_name(),
                questions=forgery_py.lorem_ipsum.sentence(),
                state=0,
                timestamp=forgery_py.date.date(True))
            db.session.add(info)
            try:
                db.session.commit()
            except IntegrityError:
                db.session.rollback()


class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32))
    username = db.Column(db.String(32), unique=True)
    password_hash = db.Column(db.String(128), unique=True)
    authorization = db.Column(db.Integer, default=0)
    infos = db.relationship('Info', backref='woker')

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    def generate_auth_token(self, expiration):
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'id': self.id})

    def is_anonymous(self):
        return False

    def to_json(self):
        if self.authorization == 0:
            authorization = '干事'
        else:
            authorization = '部长'
        json_user = {
            'name': self.name,
            'username': self.username,
            'who': authorization
        }
        return json_user

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return None
        return User.query.get(data['id'])

    def __repr__(self):
        return '<User %r>' %self.name